"use strict";

/**
 * @ngdoc function
 * @name jgappApp.controller:FilemoduleIndexCtrl
 * @description
 * # FilemoduleIndexCtrl
 * Controller of the jgappApp
 */
angular
  .module("jgappApp")
  .controller("FilemoduleIndexCtrl", function(
    $scope,
    $routeParams,
    Util,
    OpenFile,
    FileService,
    DataService,
    openApi
  ) {
    var param = {};
    param.refId = $routeParams.refId;
    param.formKey = $routeParams.formKey;
    var getFolderList = function(folderId) {
      DataService.getData(
        openApi.getFolderlist,
        angular.extend(
          {
            folderId: folderId
          },
          param
        )
      ).then(function(data) {
        $scope.fileList = data.datas;
        $scope.curID = data.folderId;
        $scope.parentFolderId = data.parentFolderId;
        $scope.folderName = data.folderPaths.pop().name;
      });
    };
    $scope.itemClick = function(item) {
      if (item.isFolder) {
        getFolderList(item.pkId);
      } else {
        if (item.canBePreview) {
          OpenFile.openFile({
            folderId: $scope.curID,
            fileId: item.pkId
          }).then(function(href) {
            var newhref=href.replace("https","http");
            var url = openApi.previewFolderFile + "?furl=" + newhref+"&"+NativeUtil.getSignStr();
            OpenFile.showFile(url);
          });
        } else if (Util.isImage(item.fileType)) {
          // 预览图片
          OpenFile.openFile({
            folderId: $scope.curID,
            fileId: item.pkId
          }).then(function(href) {
            FileService.showfile(href);
          });
        } else {
          Util.Toast("该文件无法预览");
        }
      }
    };
    $scope.goPreFolder = function() {
      getFolderList($scope.parentFolderId);
    };
    $scope.uploadfile = function() {
      var param = {
        num: 8,
        type: 1,
        data: {
          url: openApi.uploadFile2,
          param: {
            refId: $routeParams.refId,
            formKey: $routeParams.formKey,
            folderId: $scope.curID
          }
        }
      };
      NativeUtil.use(
        "choosePhoto",
        function(data) {
          getFolderList($scope.curID);
        },
        param
      );
    };
    var init = function() {
      DataService.getData(openApi.getRootFolder, param).then(function(data) {
        if (data.hasReadPermission) {
          getFolderList(data.folderId);
          $scope.rootFolderId = data.folderId;
        } else {
          Util.Toast("您没有文件查看权限", {
            callback: Util.goBack
          });
        }
        // 上传文件权限
        $scope.hasFilePermission = data.hasFilePermission;
      });
    };

    init();
  });
